package ccuserinterface;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import datamodels.Conference;
import datamodels.GlobalDataStore;
import datamodels.Manuscript;
import datamodels.Role;
import datamodels.User;

/**
 * This will handle the GUI for the 3rd user story. 
 * an author submit a paper. It has the function of a user submit the paper, and the function
 * that the user can remove their previous submitted paper.
 * @author Rithy Chhen
 *
 */
//for the submitting manuscript.
@SuppressWarnings("serial")
public class SubmittingFrame extends JFrame {
	
	private GlobalDataStore my_data_store;
	private JButton my_upload;
	private Conference my_conference;
	private User my_user;
	private Role my_role;
	private JTextArea my_content;
	private String my_title;
	private JTextField my_title_box;
	/** constructor of the frame */
	public SubmittingFrame(Conference the_conference, User the_user, Role the_role, GlobalDataStore the_data_store) {
		my_data_store = the_data_store;//anthony
		my_conference = the_conference;
		my_user = the_user;
		my_role = the_role;
		setLayout(null);
		setVisible(true);
		setTitle("Submit Manuscript");
		setPreferredSize(new Dimension(500,400));
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setUpFrame();
		setResizable(false);
		pack();
	}
	/**
	 * set up the entire frame for the submitting a manuscript page.
	 * @author Rithy Chhen. 
	 * @version 11/24/2011. 
	 * 
	 */
	private void setUpFrame() {
		JLabel conferenceName = new JLabel(my_conference.getName());
		conferenceName.setBounds(25, 25, 200, 20);
		add(conferenceName);
		JButton editMan = new JButton("Edit");
		editMan.setBounds(200, 5, 100, 20);
		editMan.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				EditMans();
			}
			
		});
		add(editMan);
		//Remove manuscript button that will take you to remove page.
		JButton authorMan = new JButton("Remove");
		authorMan.setBounds(305, 5 , 100, 20);
		authorMan.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				//this where we can remove a manuscript from the conferences. 
				RemoveMans();
			}	
		});
		//the log out button that will take u back to the main screen.
		JButton logOut = new JButton("Log Out");
		logOut.setBounds(410, 5 , 80 , 20);
		logOut.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub   
                int option = JOptionPane.showConfirmDialog(null,"Are you sure you want to log out?", 
                		"Confirm", JOptionPane.YES_NO_OPTION);
                if (option == 0) {
                	dispose(); 
                	new ConferenceCreatorStart();
                }
			}
		});
		add(logOut);
		add(authorMan);
		
		JLabel titleName = new JLabel("Title:");
		titleName.setBounds(25, 50, 40, 20);
		add(titleName);
		my_title_box = new JTextField(); 
		my_title_box.setBounds(105, 50, 300, 20);
		add(my_title_box);
		JLabel fileName = new JLabel("Filename:");
		fileName.setBounds(25, 75, 80, 20);
		add(fileName);
		final JTextField filetext = new JTextField(); 
		filetext.setEditable(false);
		filetext.setBounds(105, 75, 300, 20);
		add(filetext);
		
		my_content = new JTextArea();
		my_upload = new JButton("Choose a file");
		my_upload.setBounds(110, 100, 150, 20);
		my_upload.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e){
				
				my_content.setText("");
				JFileChooser chooser = new JFileChooser();
				int retval = chooser.showOpenDialog(null);
				if (retval == JFileChooser.APPROVE_OPTION) {
				    File myFile = chooser.getSelectedFile();
				    String full_name = myFile.getName();
				    filetext.setText(full_name);
				    String file_extension = full_name.substring(full_name.length()-3);
				    if (!file_extension.equals("txt"))
				    {
						JOptionPane.showMessageDialog(null, "Please submit a txt file!!");
				    	return;
				    } else if (myFile.canRead()) {
				    	try {
							read(myFile);
							SubmitManuscript(); 
							pack();
							
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
				    }
				    
				}
			}
		});
		this.add(my_upload);
	}
	/** Read the contents of the given file. at the same time creating the necessary representation
	 * of the contents inside the GUI. using the TextArea to display the content parsed from the text file 
	 * @author Rithy Chhen
	 * @version 11/25/2011
	 * @return the content of the input text file in form of a string representation. */
	  private void read(File the_file) throws IOException {
		JLabel manuscript_content = new JLabel("Your manuscript Content:");
	    StringBuilder text = new StringBuilder();
	    String NL = System.getProperty("line.separator");
	    Scanner scanner = new Scanner(new FileInputStream(the_file));
	    int counter = 0;
	    try {
	      while (scanner.hasNextLine()){
	    	  counter++;
	        text.append(scanner.nextLine() + NL);
	      }
	    }
	    finally{
	      scanner.close();
	    }
	  //manuscript_content.set
		add(manuscript_content);
		manuscript_content.setBounds(25, 125, 200, 20);
		my_content.setText(text.toString());
		my_content.setLineWrap(true);
		my_content.setWrapStyleWord(true);
		my_content.setEditable(false);
		JScrollPane scroll = new JScrollPane(my_content);
		scroll.setBounds(25, 150, 450, 200);
		add(scroll);
	  }
	  /**
	   * submitting a manuscript to the conference. 
	   * @author Rithy Chhen. 
	   * @version 11/25/2011
	   */
	  private void SubmitManuscript() {
		JButton my_submit = new JButton("SUBMIT");
		my_submit.setBounds(300, 100 , 100, 20);
		my_submit.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				//on success.
				if (my_role == Role.AUTHOR) {
					my_title = my_title_box.getText();
					Manuscript man = new Manuscript(my_user, my_content.getText());
					man.setTitle(my_title);
					//add the manuscript into the conference
					my_data_store.getCurrentConference().addMan(man);
					my_data_store.addConferenceObject(my_data_store.getCurrentConference());//save the data
					JOptionPane.showMessageDialog(null, "You have succesfully submitted your manuscript to the conference.");	
					my_title_box.setText("");
					
				}
				//failure.
				else {
					JOptionPane.showMessageDialog(null, "Either permission or file issues have made uploading the manuscript invalid.");
				}
			}
		});
		add(my_submit);
	  
	  }
	  /** this method allow author to remove what they have submitted, 
	   *  change the manuscripts by that author.*/
	  private void RemoveMans() {
		final JFrame remove_frame = new JFrame();
		JPanel panel = new JPanel();
		panel.setBackground(Color.WHITE);
		panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.Y_AXIS));
		JScrollPane pane = new JScrollPane(panel);
		
		remove_frame.add(pane);
		remove_frame.setSize(new Dimension(500,400));
		remove_frame.setVisible(true); 
		remove_frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		remove_frame.setTitle("Manuscripts");
		remove_frame.setResizable(false);
		pack();
		JLabel manuscript = new JLabel("Your Manuscripts");
		panel.add(manuscript);
		//a list of manuscript title.
		final List<String> list = new ArrayList<String>();
		for (int i = 0; i < my_data_store.getCurrentConference().getManuscriptsByAuthor(my_user).size(); i++) {
			//create a check box for each manuscript by the current user.
			final JCheckBox input = new JCheckBox(my_data_store.getCurrentConference().getManuscriptsByAuthor(my_user).get(i).getTitle());
			input.addActionListener(new ActionListener() {
				//When the item is selected then add it to the list. where we later use for the removing. 
				@Override
				public void actionPerformed(ActionEvent arg0) {
					if(input.isSelected()) {
						list.add(input.getText());
					} else {
						list.remove(input.getText());
					}
				}
			});
			panel.add(input);
		}
		//a button for remove action. 
		//this allow the author to remove his/her previous manuscript submitted. 
		JButton remove = new JButton("REMOVE");
		panel.add(remove);
		remove.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				//it works.
				for (int i = 0; i < my_data_store.getCurrentConference().getManuscriptsByAuthor(my_user).size(); i++) {
					for (int j = 0; j < list.size(); j++) {
						if(my_data_store.getCurrentConference().getManuscriptsByAuthor(my_user).get(i).getTitle().equals(list.get(j))) {
							//remove me?
							Manuscript man = my_data_store.getCurrentConference().getManuscriptsByAuthor(my_user).get(i);
							my_data_store.getCurrentConference().removeManuscript(man);
						}
					}
				}
				my_data_store.addConferenceObject(my_data_store.getCurrentConference());//save the data
				remove_frame.dispose();
			}
		});
	  }
	  /** edit the author manuscript. */
	  private void EditMans() {
		  
		  	JFrame edit_frame = new JFrame(); 
		  	edit_frame.setLayout(null);
			edit_frame.setVisible(true);
			edit_frame.setTitle("Edit your manuscript");
			edit_frame.setPreferredSize(new Dimension(500,400));
			edit_frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
			edit_frame.setResizable(false);
			setUpEditFrame(edit_frame);
			
			
	  }
	  private void setUpEditFrame(final JFrame edit_frame) {
		//the log out button that will take u back to the main screen.
			
			JLabel select_man = new JLabel("Select a manuscript: ");
			select_man.setBounds(10, 30, 400, 20);
			edit_frame.add(select_man);
			JPanel panel = new JPanel();
			panel.setBackground(Color.WHITE);
			panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.Y_AXIS));
			JScrollPane pane = new JScrollPane(panel);
			pane.setBounds(100, 60, 375, 100);
			edit_frame.add(pane);
			
			//for the title.
			final JTextField title = new JTextField();
			title.setBounds(100, 170, 375, 20);
			edit_frame.add(title);
			
			final JTextArea area_1 = new JTextArea();
			area_1.setBackground(Color.WHITE);
			area_1.setEditable(true);
			JScrollPane pane1 = new JScrollPane(area_1);
			pane1.setBounds(100, 200, 375, 150);
			edit_frame.add(pane1);
			JButton save = new JButton("Save");
			save.setBounds(10, 170, 80, 20);
			save.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					
					if (my_title != null) {
						for (int i = 0; i < my_conference.getManuscriptsByAuthor(my_user).size(); i++) {
							if (my_title.equals(my_conference.getManuscriptsByAuthor(my_user).get(i).getTitle())) {
								my_conference.getManuscriptsByAuthor(my_user).get(i).setTitle(title.getText());
								my_conference.getManuscriptsByAuthor(my_user).get(i).setText(area_1.getText());
								my_data_store.addConferenceObject(my_data_store.getCurrentConference());//save the data
								edit_frame.dispose();						
						}
					}
					} else {
						JOptionPane.showMessageDialog(null, "Please select a manuscript and then press edit");
					}
				}
			});
			edit_frame.add(save);
			JButton edit = new JButton("Edit");
			edit.setBounds(10, 60, 80, 20);
			edit.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					
					if (my_title != null) {
						for (int i = 0; i < my_conference.getManuscriptsByAuthor(my_user).size(); i++) {
						
							if (my_title.equals(my_conference.getManuscriptsByAuthor(my_user).get(i).getTitle())) {
								title.setText(my_conference.getManuscriptsByAuthor(my_user).get(i).getTitle());
								area_1.setText(my_conference.getManuscriptsByAuthor(my_user).get(i).getText());
								area_1.setLineWrap(true);
								area_1.setWrapStyleWord(true);
							}
						}
					} else {
							JOptionPane.showMessageDialog(null, "Please Select a Manuscript");
						
					}
				}
				
			});
			edit_frame.add(edit);
			ButtonGroup group = new ButtonGroup();
			for (int i = 0; i < my_conference.getManuscriptsByAuthor(my_user).size(); i++) {
				final JCheckBox box = new JCheckBox(my_conference.getManuscriptsByAuthor(my_user).get(i).getTitle());
				box.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						if(box.isSelected()) {
							my_title = box.getText();
						}
						
					}
					
				});
				group.add(box);
				panel.add(box);
			}
			edit_frame.pack();
	  }
}
